/**
 * author: leunpha date: 2014-5-1 version 2.0 dependency: jquery.js
 */
(function($) {
	
	$.upload = function (options) {
	    var settings = {
	        action: "",
	        fileName: "file",
	        params: {},
	        accept: ".jpg,.png",
	        ieSubmitBtnText: "上传",
			dataType:"text",
			mask:true,
	        complete: function (result) {
				alert(result);
	        },
	        submit: function () {
	        }
	    }
	    settings = $.extend(settings, options);
	
	    var iframeName = "cch_upload_iframe";
	    var iframLoadCnt = 0;
	    $("#"+iframeName).remove();
	    var iframe = $("<iframe name='"+iframeName+"' style='display:none;' id='"+iframeName+"' src='about:blank'></iframe>");
	    $("body").append(iframe);
		
	    var form = $("<form></form>");
	    form.attr({
	        target: iframeName,
	        action: settings.action,
	        method: "post",
	        "class": "ajax_form",
	        enctype: "multipart/form-data"
	    });
	    
		var input = $("<input type='file'/>");
		input.attr({
			accept : settings.accept,
			name : settings.fileName
		});
		input.change(function() {
			settings.submit.call(form);
			if(settings.mask){
				$.messager.progress();
			}
			$(this).parent("form").submit();
		});
	    form.append(input);
	    for (var param in settings.params) {
	        var div = $("<input type='hidden'/>").attr({name: param, value: settings.params[param]});
	        input.after(div)
	        div = null;
	        delete div;
	    } 

		iframe.load(function() {
			iframLoadCnt++;
			if(iframLoadCnt==1){
				iframe.contents().find("body").append(form);
			    input.click();
			}
			if (iframLoadCnt == 2) {
				var text = iframe.contents().find("body").text();
				var dataType = settings.dataType.toLocaleUpperCase();
				iframe.remove();
				$.messager.progress("close");
				if (text && typeof text == "string" && dataType == "JSON") {
					try {
						text = $.parseJSON(text);
					} catch (e) {
						text = "error";
					}
				}
				settings.complete.call(null, text);
			}
		});
	}
})(jQuery);